package cn.kgc.controller;

import cn.kgc.commons.annotation.IgnoreResultAdviceAnnotation;
import cn.kgc.config.AlipayTemplate;
import cn.kgc.constant.OrderStatusEnum;
import cn.kgc.entity.OmsOrder;
import cn.kgc.service.OmsOrderService;
import cn.kgc.vo.PayVo;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 王跃
 */
@RequestMapping("/order")
@RestController
public class AlipayController {

    @Resource
    private AlipayTemplate alipayTemplate;

    @Resource
    private OmsOrderService omsOrderService;

    //1 支付接口
    // http://localhost:8087/order/pay?orderSn=xxxxxxxxxx

    @GetMapping("/pay")
    @IgnoreResultAdviceAnnotation
    public String payOrder(@RequestParam(name = "orderSn")
                                       String orderSn)throws Exception{

        LambdaQueryWrapper<OmsOrder> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OmsOrder::getOrderSn,orderSn);
        OmsOrder omsOrder= omsOrderService.getOne(lambdaQueryWrapper);
        String totalAmount=
                omsOrder.getTotalAmount().setScale(2, RoundingMode.UP)
                .toString();

        PayVo payVo=new PayVo();
        payVo.setOut_trade_no(orderSn);
        payVo.setSubject(orderSn);
        payVo.setBody("");
        payVo.setTotal_amount(totalAmount);
        return alipayTemplate.pay(payVo);
    }

    //收集阿里调用我们接口的请求中的参数
    private Map<String,String> getRequestParams(HttpServletRequest request){
        Map<String,String> map=new HashMap<>();
        Map<String,String[]> parameterMap=request.getParameterMap();
        Iterator<String> iterator= parameterMap.keySet().iterator();
        while(iterator.hasNext()){
           String key= iterator.next();
           String [] values=  parameterMap.get(key);
           String value=StringUtils.arrayToDelimitedString(values,";");
           map.put(key,value);
        }
        return map;
    }

    @GetMapping("/returnUrl")  //2 阿里调用我们的同步接口
    @IgnoreResultAdviceAnnotation
    public String returnUrl(HttpServletRequest request){
        //打开订单支付成功的确认页面,确认是阿里调用我们的接口。(验签)
        Map<String,String> params= getRequestParams(request);
        boolean flag= false;
        try {
            flag = AlipaySignature.rsaCheckV1(params, AlipayTemplate.ALIPAY_PUBLIC_KEY,
                    AlipayTemplate.CHARSET,AlipayTemplate.SIGNTYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(flag){
            //回到一个订单支付成功的确认页面上
            return "success";
        }else{
            return "failure";
        }
    }

    //3异步接口
    @PostMapping("/notifyUrl")  //2 阿里调用我们的同步接口
    @IgnoreResultAdviceAnnotation
    public String notifyUrl(HttpServletRequest request){
        //1 验签
        Map<String,String> params= getRequestParams(request);
        String tradeStatus=params.get("trade_status"); //订单的状态
        String outTradeNo=params.get("out_trade_no"); //订单编号
        boolean flag= false;
        try {
            flag = AlipaySignature.rsaCheckV1(params, AlipayTemplate.ALIPAY_PUBLIC_KEY,
                    AlipayTemplate.CHARSET,AlipayTemplate.SIGNTYPE);
            if(flag){
                //2 阿里通知我们的订单的状态(参数)
                if(tradeStatus.equals("TRADE_FINISHED")||
                           tradeStatus.equals("TRADE_SUCCESS")){
                    //更新订单的状态
                    LambdaQueryWrapper<OmsOrder> lambdaQueryWrapper=new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(OmsOrder::getOrderSn,outTradeNo);
                    OmsOrder omsOrder= omsOrderService.getOne(lambdaQueryWrapper);
                    //更改状态为已经付款
                    omsOrder.setStatus(OrderStatusEnum.PAID.getOrderStatus());
                    omsOrderService.updateById(omsOrder);
                    return "success";
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "failure";
    }
    //http://localhost:8087/order/pay?orderSN=5e946889f8df47ada8e9fd02fc189375
}
